/* Filename: ping.c
 * Description: gcc -Wall ping.c -o ping
 * Last modified: humble 2021-01-28 09:22:42
 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

static void usage(void)
{
#define USAGE "Usage:\n\
    ./ping <ip>\n\
    Version 1.0.0\n"
    printf(USAGE);
}

static int test_ping1(const char *ipstr)
{
    char cmd[256] = {0};
    sprintf(cmd, "ping %s -c2 -w2 > /dev/null 2>&1", ipstr);
    printf("cmd:%s\n", cmd);
    if(system(cmd) != 0){ return -1; }
    return 0;
}


#define BUFLEN 1024

int test_ping2(const char *ipstr)
{
    int pipe_arr[2];
    char buf[BUFLEN];

    //Create pipe - pipe_arr[0] is "reading end", pipe_arr[1] is "writing end"
    pipe(pipe_arr);

    if(fork() == 0){ //child
        dup2(pipe_arr[1], STDOUT_FILENO);
        execl("/sbin/ping", "ping", "-c 1", ipstr, (char*)NULL);
    }
    else{ //parent
        wait(NULL);
        read(pipe_arr[0], buf, BUFLEN);
        printf("%s\n", buf);
    }
    close(pipe_arr[0]);
    close(pipe_arr[1]);
    return 0;
}

int main(int argc, char **argv)
{
    if(argc != 2){ fprintf(stderr, "argc!=2\n"); usage(); exit(1); }
    printf("==========test_ping1\n");
    if(test_ping1(argv[1]) < 0){ printf("failed\n"); }
    else{ printf("ok\n"); }
    printf("==========test_ping2\n");
    if(test_ping2(argv[1]) < 0){ printf("failed\n"); }
    else{ printf("ok\n"); }
    return 0;
}
